#pragma once

#include <sys/timeb.h>
#include <deque>
#include "TimeControls.h"

namespace My {

class FramerateCalculator {
public:
	/// calculates framerate according to previous notes
	float Calc() const {
		if (m_FrameTimes.size() <= 1)
			return 0;
		return float(1000 * (m_FrameTimes.size() - 1) / (m_FrameTimes.back() - m_FrameTimes.front()));
	}
	void SetFramerate(My::TimeControls & tc) const {
		float fps = Calc();
		if (fps == 0)
			tc.ClearRealFramerate();
		else
			tc.SetRealFramerate(fps);
	}
	/// makes a note that else one frame was output
	void Frame() {
		_timeb now;
		_ftime(&now);
		double last = now.time * 1000. + now.millitm;
		m_FrameTimes.push_back(last);
		//consider at least 3 frames and preferably only frames rendered within last second
		while (m_FrameTimes.size() > 3 && last - m_FrameTimes.front() > 1000)
			m_FrameTimes.pop_front();
	}
private:
	/// here stored times (in milliseconds) when frame rendering (loading) is finished
	std::deque<double>	m_FrameTimes;
};

} //namespace My
